<?php

namespace App\Api\Controllers\LeshuaUnion;

use App\Api\Controllers\Config\LeshuaUnionPayConfigController;
use App\Api\Controllers\Merchant\PayBaseController;
use App\Common\PaySuccessAction;
use App\Common\RefundSuccessAction;
use App\Exceptions\BizException;
use App\Models\Merchant;
use App\Models\MerchantWalletDetail;
use App\Models\RefundOrder;
use App\Models\RefundOrderDoing;
use App\Models\Store;
use App\Models\StorePayWay;
use App\Models\UserRate;
use App\Models\UserWalletDetail;
use App\Services\Pay\ResultVo;
use Illuminate\Support\Facades\Log;

class LogicController extends BaseController
{
    public function __construct()
    {

    }

    public function qrSubmitParams($data_insert, $data)
    {
        $payConfig = new \App\Api\Controllers\Config\LeshuaUnionPayConfigController();
        $config = $payConfig->config($data['config_id']);
        if (!$config) {
            return json_encode([
                'status' => 2,
                'message' => '乐刷支付配置不存在请检查配置'
            ]);
        }
        $merchant = $payConfig->merchant($data['store_id'], $data['store_pid']);
        if (!$merchant) {
            return json_encode([
                'status' => 2,
                'message' => '乐刷支付商户号不存在'
            ]);
        }
        //微信
        if ($data['ways_type'] == '140001') {
            $pay_ways = "WXZF";
            $out_trade_no = 'wx_qr' . date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
            //入库参数
            $data_insert['ways_type'] = $data['ways_type'];
            $data_insert['ways_type_desc'] = '微信支付';
            $data_insert['ways_source'] = 'weixin';
            $data_insert['ways_source_desc'] = '微信支付';
            $data_insert['out_trade_no'] = $out_trade_no;
        }
        //支付宝
        if ($data['ways_type'] == '140002') {
            $pay_ways = "ZFBZF";
            $out_trade_no = 'ali_qr' . date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
            //入库参数
            $data_insert['ways_type'] = $data['ways_type'];
            $data_insert['ways_type_desc'] = '支付宝';
            $data_insert['ways_source'] = 'alipay';
            $data_insert['ways_source_desc'] = '支付宝';
            $data_insert['out_trade_no'] = $out_trade_no;
        }
        //云闪付
        if ($data['ways_type'] == '140003') {
            $pay_ways = "UPSMZF";
            $out_trade_no = 'un_qr' . date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
            //入库参数
            $data_insert['ways_type'] = $data['ways_type'];
            $data_insert['ways_type_desc'] = '银联支付';
            $data_insert['ways_source'] = 'unionpay';
            $data_insert['ways_source_desc'] = '银联支付';
            $data_insert['out_trade_no'] = $out_trade_no;
        }


        $payData = [
            "mch_id" => $merchant->mch_id,
            "out_trade_no" => $out_trade_no,
            "total_amount" => $data['total_amount'],
            "pay_way" => $pay_ways
        ];

        //单品
        $isGoods = 2;
        if (isset($data['store_id']) && !empty($data['store_id'])) {
            $isGoods = \App\Models\Store::where('store_id', $data['store_id'])->value('is_goods');
        }
        $data['goods_detail'] = $couponDetail = '';
        if (!empty(request('goods'))) {
            $goods = json_decode(request('goods'), true);
            unset($data['goods']);
            $goods_detail = array();
            foreach ($goods as $k => $v) {
                $goods_detail[$k]['goods_name'] = $v['goods_name'];
                $goods_detail[$k]['quantity'] = intval($v['count']);
                $goods_detail[$k]['price'] = bcmul((string)$v['goods_price'] ,"100");
                $goods_detail[$k]['goods_id'] = $v['goods_code'];
            }
            $Detail['receipt_id'] = time();
            $Detail['goods_detail'] = $goods_detail;
            $Detail['cost_price'] = bcmul((string)$data['total_amount'] , "100");
            $couponDetail = json_encode($Detail, JSON_UNESCAPED_UNICODE);
        }
        Log::channel("leshuaunion")->info("qr_goods_detail", [
            "str" => $couponDetail,
            "isGoods" => $isGoods
        ]);
        /*
        if (isset($couponDetail['goods_detail']) && !empty($couponDetail['goods_detail']) && $isGoods == 1) {
            $goods_detail = [];
            foreach ($couponDetail['goods_detail'] as $k => $v) {
                $goods_detail[$k]['goodsName'] = $v['goods_name'];
                $goods_detail[$k]['quantity'] = $v['quantity'];
                $goods_detail[$k]['price'] = $v['price'];
                $goods_detail[$k]['goodsId'] = (string)$v['goods_id'];
            }
            $Detail['receipt_id'] = (string)$couponDetail['receipt_id'];
            $Detail['goods_detail'] = $goods_detail;
            $Detail['cost_price'] = $couponDetail['cost_price'];
            $payData['goods_detail'] = json_encode($Detail, JSON_UNESCAPED_UNICODE);
        }
        */
        if (!empty($couponDetail) && $isGoods == 1) {
            $goods = json_decode($couponDetail, true);
            Log::channel("leshuaunion")->info("qr_goods_arr", $goods);
            $goodsArr = [];
            foreach ($goods['goods_detail'] as $v) {
                $goodsArr[] = [
                    'quantity' => $v['quantity'],
                    'goods_id' => $v['goods_id'],
                    'price' => $v['price'],
                    'goods_name' => $v['goods_name'],
                ];
            }
            $costPrice = $goods['cost_price'];
//            $costPrice = number_format($costPrice, 2, '.', '');
            $couponDetail = json_encode([
                'cost_price' => $costPrice,
                'receipt_id' => (string)$goods['receipt_id'],
                'goods_detail' => $goodsArr,
            ]);
//            $payData['goodsTag'] = '00';
            $payData['goods_detail'] = $couponDetail;
        }
        Log::channel("leshuaunion")->info("qr_submit_before", $payData);
        $return = (new PayController())->qr_submit($payData, $config);
        if ($return['status'] == 1) {
            $insert_re = (new \App\Api\Controllers\BaseController())->insert_day_order($data_insert);
            if (!$insert_re) {
                return json_encode([
                    'status' => 2,
                    'message' => '订单未入库'
                ]);
            }
            return json_encode([
                'status' => 1,
                'data' => $return['data']
            ]);
        } else {
            return json_encode([
                'status' => 2,
                'message' => $return['message']
            ]);
        }
    }


    public function payParams($data_insert, $data)
    {
        $store_id = $data['store_id'] ?? '';
        $store_pid = $data['store_pid'] ?? '';
        $merchant_id = $data['merchant_id'] ?? '';
        $total_amount = $data['total_amount'] ?? '';
        $ways_type = $data['ways_type'] ?? '';
        $store_name = $data['store_name'] ?? '';
        $config_id = $data['config_id'] ?? '';
        $ways_type_desc = $data['ways_type_desc'] ?? '';
        $ways_source = $data['ways_source'] ?? '';
        $title = $data['title'] ?? '';
        $tg_user_id = $data['tg_user_id'] ?? '';
        $out_trade_no = $data['out_trade_no'] ?? '';
        $code = $data['code'] ?? '';
        $company = $data['company'] ?? '';
        $ways_source_desc = $data['ways_source_desc'] ?? '';
        $device_id = $data['device_id'] ?? ''; //终端设备号.注:当中国银联时,为必填

        $payConfig = new LeshuaUnionPayConfigController();
        $config = $payConfig->config($data['config_id']);
        if (!$config) {
            return json_encode([
                'status' => 2,
                'message' => '乐刷配置不存在请检查配置'
            ]);
        }
        $merchant = $payConfig->merchant($data['store_id'], $data['store_pid']);
        if (!$merchant) {
            return json_encode([
                'status' => 2,
                'message' => '乐刷商户号不存在'
            ]);
        }

        //入库参数
        $data_insert['out_trade_no'] = $out_trade_no;
        $data_insert['ways_type'] = $ways_type;
        $data_insert['ways_type_desc'] = $ways_type_desc;
        $data_insert['ways_source'] = $ways_source;
        $data_insert['company'] = $company;
        $data_insert['ways_source_desc'] = $ways_source_desc;

        $insert_re = (new \App\Api\Controllers\BaseController())->insert_day_order($data_insert);
        if (!$insert_re) {
            return json_encode([
                'status' => 2,
                'message' => '订单未入库'
            ]);
        }

        $payData = [
            "mch_id" => $merchant->mch_id,
            "out_trade_no" => $out_trade_no,
            "desc" => $title,
            "terminal_id" => $device_id,
            "total_amount" => $total_amount,
            "code" => $code,
            'ways_source' => $ways_source
        ];

        //单品
        $isGoods = 2;
        if (isset($data['store_id']) && !empty($data['store_id'])) {
            $isGoods = \App\Models\Store::where('store_id', $data['store_id'])->value('is_goods');
        }
        $couponDetail = '';
        if (isset($data['couponDetail']) && !empty($data['couponDetail'])) {
            $couponDetail = json_decode($data['couponDetail'], true);
            Log::channel("leshuaunion")->info("scan_Request_goods", $couponDetail);
        }

        if (isset($couponDetail['goods_detail']) && !empty($couponDetail['goods_detail']) && $isGoods == 1) {
            $goods_detail = [];
            foreach ($couponDetail['goods_detail'] as $k => $v) {
                $goods_detail[$k]['goods_name'] = $v['goods_name'];
                $goods_detail[$k]['quantity'] = $v['quantity'];
                $goods_detail[$k]['price'] = (float)$v['price'];
                $goods_detail[$k]['goods_id'] = (string)$v['goods_id'];
            }
            $Detail['receipt_id'] = (string)$couponDetail['receipt_id'];
            $Detail['goods_detail'] = $goods_detail;
            $Detail['cost_price'] = (float)$couponDetail['cost_price'];
            $payData['goods_detail'] = json_encode($Detail, JSON_UNESCAPED_UNICODE);
        }

        $return = (new PayController())->scan_pay($payData, $config);
        //返回支付成功
        if ($return['status'] == 1) {
            $trade_no = isset($return['data']['trade_no']) ? $return['data']['trade_no'] : '';
            $buyer_user_id = '';
            $other_no = isset($return['data']['other_no']) ? $return['data']['other_no'] : '';
            if (!empty($return['data']['buyer_id'])) {
                $buyer_user_id = $return['data']['buyer_id'] ?? "";
            }
            $pay_time = $return['data']['pay_time'];
            $buyer_pay_amount = $return['data']['pay_amount'];

            $update_data = [
                'trade_no' => $trade_no,
                'other_no' => $other_no,
                'buyer_id' => $buyer_user_id,
                'status' => '1',
                'pay_status_desc' => '支付成功',
                'pay_status' => 1,
                'payment_method' => '', //credit：信用卡 pcredit：花呗（仅支付宝） debit：借记卡 balance：余额 unknown：未知
                'pay_time' => $pay_time,
                'buyer_pay_amount' => $buyer_pay_amount //用户实际支付
            ];
            (new \App\Api\Controllers\BaseController())->update_day_order($update_data, $out_trade_no);

            //支付成功后的动作
            $data = [
                'ways_type' => $data['ways_type'],
                'ways_type_desc' => $data['ways_type_desc'],
                'company' => $data_insert['company'],
                'source_type' => '140001', //返佣来源
                'source_desc' => '乐刷联合收单', //返佣来源说明
                'total_amount' => $total_amount,
                'other_no' => $data_insert['other_no'],
                'out_trade_no' => $out_trade_no,
                'rate' => $data_insert['rate'],
                'fee_amount' => $data_insert['fee_amount'],
                'merchant_id' => $merchant_id,
                'store_id' => $store_id,
                'user_id' => $tg_user_id,
                'config_id' => $config_id,
                'store_name' => $store_name,
                'ways_source' => $data['ways_source'],
                'pay_time' => $pay_time,
                'device_id' => isset($data['device_id']) ? $data['device_id'] : "",
            ];
            PaySuccessAction::action($data);

            return json_encode([
                'status' => 1,
                'pay_status' => '1',
                'message' => '支付成功',
                'data' => [
                    'out_trade_no' => $out_trade_no,
                    'ways_type' => $ways_type,
                    'total_amount' => $total_amount,
                    'store_id' => $store_id,
                    'store_name' => $store_name,
                    'config_id' => $config_id,
                    'pay_time' => $pay_time,
                    'trade_no' => $trade_no,
                    'ways_source' => $data['ways_source'],
                ]
            ]);
        } elseif ($return['status'] == 2) {
            return json_encode([
                'status' => 1,
                'pay_status' => 2,
                'message' => '支付中',
                'data' => [
                    'out_trade_no' => $out_trade_no,
                    'ways_type' => $ways_type,
                    'ways_source' => $data['ways_source'],
                    'total_amount' => $total_amount,
                    'store_id' => $store_id,
                    'store_name' => $store_name,
                    'config_id' => $config_id,
                ]
            ]);
        } else {
            return json_encode([
                'status' => 2,
                'message' => $return['message']
            ]);
        }
    }

    public function queryParams($store_id, $store_pid, $data, $order)
    {
        try {
            $payConfig = new \App\Api\Controllers\Config\LeshuaUnionPayConfigController();
            $config = $payConfig->config($order->config_id);
            if (!$config) {
                return json_encode([
                    'status' => 2,
                    'message' => '乐刷支付配置不存在请检查配置'
                ]);
            }

            $merchant = $payConfig->merchant($store_id, $store_pid);

            if (!$merchant) {
                return json_encode([
                    'status' => 2,
                    'message' => '乐刷支付商户号不存在'
                ]);
            }


            $payData = [
                "mch_id" => $merchant->mch_id,
                "out_trade_no" => $order->out_trade_no,
                'ways_source' => $order->ways_source
            ];
            $return = (new PayController())->order_query($payData, $config);

            //返回支付成功
            if ($return['status'] == 1) {
                $trade_no = isset($return['data']['trade_no']) ? $return['data']['trade_no'] : '';
                $buyer_user_id = '';

                $other_no = $return["data"]["other_no"] ?? "";
                if (!empty($return['data']['buyer_id'])) {
                    $buyer_user_id = $return['data']['buyer_id'];
                }

                $pay_time = $return['data']['pay_time'];
                $buyer_pay_amount = $return['data']['pay_amount'];
                if ($order->pay_status != 1) {
                    $update_data = [
                        'trade_no' => $trade_no,
                        'other_no' => $other_no,
                        'buyer_id' => $buyer_user_id,
                        'status' => '1',
                        'pay_status_desc' => '支付成功',
                        'pay_status' => 1,
                        'payment_method' => '', //credit：信用卡 pcredit：花呗（仅支付宝） debit：借记卡 balance：余额 unknown：未知
                        'pay_time' => $pay_time,
                        'buyer_pay_amount' => $buyer_pay_amount //用户实际支付
                    ];
                    (new \App\Api\Controllers\BaseController())->update_day_order($update_data, $order->out_trade_no);

                    //支付成功后的动作
                    $data = [
                        'ways_type' => $order->ways_type,
                        'ways_type_desc' => $order->ways_type_desc,
                        'company' => $order->company,
                        'source_type' => '140001', //返佣来源
                        'source_desc' => '乐刷联合收单', //返佣来源说明
                        'total_amount' => $order->total_amount,
                        'other_no' => $order->other_no,
                        'out_trade_no' => $order->out_trade_no,
                        'rate' => $order->rate,
                        'fee_amount' => $order->fee_amount,
                        'merchant_id' => $order->merchant_id,
                        'store_id' => $store_id,
                        'user_id' => $order->user_id,
                        'config_id' => $order->config_id,
                        'store_name' => $order->store_name,
                        'ways_source' => $order->ways_source,
                        'pay_time' => $pay_time,
                        'device_id' => isset($data['device_id']) ? $data['device_id'] : "",
                    ];
                    PaySuccessAction::action($data);
                }
                return json_encode([
                    'status' => 1,
                    'pay_status' => '1',
                    'message' => '支付成功',
                    'data' => [
                        'out_trade_no' => $order->out_trade_no,
                        'ways_type' => $order->ways_type,
                        'total_amount' => $order->total_amount,
                        'store_id' => $store_id,
                        'store_name' => $order->store_name,
                        'config_id' => $order->config_id,
                        'pay_time' => $pay_time,
                        'trade_no' => $trade_no,
                        "other_no" => $other_no,
                        'ways_source' => $order->ways_source,
                    ]
                ]);
            } //支付中
            elseif ($return['status'] == 2) {
                return json_encode([
                    'status' => 1,
                    'pay_status' => 2,
                    'message' => '支付中',
                    'data' => [
                        'out_trade_no' => $order->out_trade_no,
                        'ways_type' => $order->ways_type,
                        'ways_source' => $order->ways_source,
                        'total_amount' => $order->total_amount,
                        'store_id' => $store_id,
                        'store_name' => $order->store_name,
                        "other_no" => $other_no ?? "",
                        'config_id' => $order->config_id
                    ]
                ]);
            } elseif ($return['status'] == 3) {
                return json_encode([
                    'status' => 1,
                    'pay_status' => 3,
                    'message' => $return['message'],
                    "data" => [
                        'out_trade_no' => $order->out_trade_no,
                        'ways_type' => $order->ways_type,
                        'ways_source' => $order->ways_source,
                        'total_amount' => $order->total_amount,
                        'store_id' => $store_id,
                        "other_no" => $other_no ?? "",
                        'store_name' => $order->store_name,
                        'config_id' => $order->config_id
                    ]
                ]);
            } else {
                return json_encode([
                    'status' => 2,
                    'message' => $return['message']
                ]);
            }
        } catch (\Exception $e) {
            return json_encode([
                'status' => -1,
                'message' => $e->getMessage() . ' | ' . $e->getLine()
            ]);
        }
    }

    public function refundParams($data, $order)
    {
        try {
            $payConfig = new \App\Api\Controllers\Config\LeshuaUnionPayConfigController();
            $config = $payConfig->config($order->config_id);
            if (!$config) {
                return json_encode([
                    'status' => 2,
                    'message' => '乐刷支付配置不存在请检查配置'
                ]);
            }
            $merchant = $payConfig->merchant($data['store_id'], $data['store_pid']);
            if (!$merchant) {
                return json_encode([
                    'status' => 2,
                    'message' => '乐刷支付商户号不存在'
                ]);
            }
            $count = RefundOrder::where(['out_trade_no' => $data['out_trade_no']])->count();

            $payData = [
                "mch_id" => $merchant->mch_id,
                "out_trade_no" => $order->out_trade_no,
                "refund_amount" => $data['refund_amount'],
                "refund_no" => $data['refund_no'],
                'new_refund_amount' => $data['new_refund_amount'],
                'new_fee_amount' => $data['new_fee_amount'],
                "ways_source" => $order->ways_source
            ];
            $return = (new PayController())->refund($payData, $config);
            //退款请求成功
            if ($return['status'] == '1') {
                $insert_data = [
                    'status' => '6',
                    'pay_status' => 6,
                    'pay_status_desc' => '已退款',
                    'refund_amount' => $data['new_refund_amount'],
                    'fee_amount' => $data['new_fee_amount']
                ];
                Log::channel("leshuaunion")->info("refund_promotion_detail", $return);
                if ($order->ways_source == 'weixin' && isset($return["data"]['refund_detail'])) {
                    \App\Common\PaySuccessAction::addCoupon($data['out_trade_no'], $return["data"]['refund_detail'], 'refund');
                }
                (new \App\Api\Controllers\BaseController())->update_day_order($insert_data, $data['out_trade_no']);
                RefundOrder::create([
                    'ways_source' => $order->ways_source,
                    'type' => $data['ways_type'],
                    'refund_amount' => $data['refund_amount'], //退款金额
                    'refund_no' => $payData['refund_no'], //平台退款单号
                    'store_id' => $data['store_id'],
                    'merchant_id' => $data['merchant_id'],
                    'out_trade_no' => $data['out_trade_no'],
                    'trade_no' => $order->trade_no,
                    "other_refund_no" => $return["data"]["other_refund_no"],
                ]);
                //退款成功后的操作
                RefundSuccessAction::action([
                    'out_trade_no' => $data['out_trade_no'],
                    'refund_no' => $payData['refund_no'], //平台退款单号
                ]);

                //返佣去掉
                UserWalletDetail::where('out_trade_no', $data['out_trade_no'])->update([
                    'settlement' => '03',
                    'settlement_desc' => '退款订单'
                ]);
                MerchantWalletDetail::where('out_trade_no', $data['out_trade_no'])->update([
                    'settlement' => '03',
                    'settlement_desc' => '退款订单'
                ]);

                $data = [
                    'refund_amount' => $data['refund_amount'],
                    'out_trade_no' => $data['out_trade_no'],
                    'refund_no' => $payData['refund_no'], //平台退款单号
                    'other_no' => $order->trade_no
                ];
                return json_encode([
                    'status' => '1',
                    'message' => '退款成功',
                    'data' => $data
                ]);
            } //退款处理中
            elseif ($return['status'] == '3') {
                $insert_data = [
                    'status' => '5',
                    'pay_status' => 5,
                    'pay_status_desc' => '退款中'
                ];
                $res = (new \App\Api\Controllers\BaseController())->update_day_order($insert_data, $data['out_trade_no']);
                if (!$res) {
                    Log::info('乐刷-退款中-更新失败');
                }
                RefundOrderDoing::query()->create([
                    "company" => $order->company,
                    'ways_source' => $order->ways_source,
                    'type' => $data['ways_type'],
                    'refund_amount' => $data['refund_amount'], //退款金额
                    'refund_no' => $payData['refund_no'] ?? "", //平台退款单号
                    'store_id' => $data['store_id'],
                    'merchant_id' => $data['merchant_id'],
                    'out_trade_no' => $data['out_trade_no'],
                    'trade_no' => $order->trade_no,
                    "other_refund_no" => $return["data"]["other_refund_no"],
                ]);
                $refund_count = $return['data']['refund_count'] - 1; //退款记录数
                $data = [
                    'refund_amount' => $data['refund_amount'],
                    'out_trade_no' => $data['out_trade_no'],
                    'refund_no' => $return['data']['refund_id_' . $refund_count] ?? "", //平台退款单号
                    'other_no' => $order->trade_no
                ];
                return json_encode([
                    'status' => '1',
                    'message' => '退款中',
                    'data' => $data
                ]);
            } else {

                //其他情况
                $message = $return['message'];
                return json_encode([
                    'status' => '2',
                    'message' => $message
                ]);
            }
        } catch (\Exception $e) {
            return json_encode([
                'status' => -1,
                'message' => $e->getMessage() . ' | ' . $e->getLine() . $e->getFile()
            ]);
        }
    }


    public function embedPay(array $data, array $config)
    {
        try {
            $response = [
                "AGET_ID" => $config["agetId"],
                "CUST_ID" => $data["custId"],
                "THREE_ORDER_NO" => $data["orderNo"],
                "TxnAmt" => $data["total_amount"],//订单金额 单位分$data["txamt"],
                "ACCESS_TYPE" => "02",
                "PAY_WAY" => "8",
                "interface" => "000002",
                "timeStamp" => date("YmdHis", time()),
                "ASYNC_NOTIFY_IP" => env("APP_URL") . "/api/leshuaunion/embedPayNotify",
                "merchant_id" => $data["merchant_id"],
                "pre_order" => ""
            ];
            $store = Store::query()->where("store_id", $data["store_id"])->first();
            if (empty($store)) {
                throw new BizException("门店不存在");
            }
            //关闭的商户禁止交易
            if ($store->is_close || $store->is_admin_close || $store->is_delete || $store->state == 3) {
                throw  new BizException("商户已经关闭");
            }
            if ($store->status != 1) {
                throw  new BizException("商户已经关闭");
            }
            list($isRun, $error) = \App\Services\Store\StoreSignService::validateSign((string)$store->store_id, (string)$data["company"]);
            if ($isRun == false) {
                throw new BizException($error);
            }

            $merchant = Merchant::query()->find($data["merchant_id"]);
            if (empty($merchant)) {
                throw new BizException("收银员不存在");
            }
            //插入数据库
            $data_insert = [
                'trade_no' => '',
                'user_id' => $store->user_id,
                'store_id' => $store->store_id,
                'store_name' => $store->store_name,
                'buyer_id' => '',
                'total_amount' => $data["total_amount"],
                'shop_price' => $data["total_amount"],
                'payment_method' => '',
                'status' => '',
                'pay_status' => 2,
                'pay_status_desc' => '等待支付',
                'merchant_id' => empty($merchant) ? 0 : $merchant->id,
                'merchant_name' => empty($merchant) ? "" : $merchant->name,
                'remark' => "",
                'device_id' => "embed",
                'config_id' => "1234",
                'other_no' => "",
                'pay_method' => "embedPay",
                "notify_url" => $data["notify_url"] ?? ""
            ];

            $ways = StorePayWay::query()
                ->where("status", 1)
                ->where("store_id", $store->store_id)
                ->where("company", $data["company"])
                ->where("ways_source", $data["ways_source"])->first();
            if (empty($ways)) {
                $storeP = Store::query()->where("id", $store->pid)->first();
                if (empty($storeP)) {
                    throw new BizException("主店不存在");
                }
                $ways = StorePayWay::query()
                    ->where("status", 1)
                    ->where("store_id", $storeP->store_id)
                    ->where("company", $data["company"])
                    ->where("ways_source", $data["ways_source"])->first();
            }
            if (empty($ways)) {
                throw new BizException("支付方式不存在");
            }

            $user_rate_obj = $this->getCostRate($ways->ways_type, $store->user_id);
            $cost_rate = $user_rate_obj ? $user_rate_obj->rate : 0.00; //成本费率
            //扫码费率入库
            if ($cost_rate) $data_insert['cost_rate'] = $cost_rate;
            $data_insert['rate'] = $ways->rate;
            $data_insert['fee_amount'] = $ways->rate * $data["total_amount"] / 100;


            $ways_source_desc = "";
            switch ($data['ways_source']) {
                case "weixin":
                    $ways_source_desc = "微信支付";
                    break;
                case "alipay":
                    $ways_source_desc = "支付宝";
                    break;
                case "unionpay":
                    $ways_source_desc = "云闪付";
                    break;
            }


            /*
                "AGET_ID" => $config["agetId"],
                 "CUST_ID" => $data["custId"],
                 "THREE_ORDER_NO" => $data["orderNo"],
                 "TxnAmt" => $data["total_amount"],//订单金额 单位分$data["txamt"],
                 "ACCESS_TYPE" => "02",
                 "PAY_WAY" => "8",
                 "interface" => "000002",
                 "timeStamp" => date("YmdHis", time()),
                 "ASYNC_NOTIFY_IP" => env("APP_URL") . "/api/leshuaunion/embedPayNotify",
                 "merchant_id" => $data["merchant_id"]
            */
            $pay = new PayController();
            $result = $pay->embedPay([
                "merchant_id" => $response["CUST_ID"],
                "amount" => $data["total_amount"],
                "third_order" => $response["THREE_ORDER_NO"],
                "shop_no" => $data["store_id"],
                "ASYNC_NOTIFY_IP" => $response["ASYNC_NOTIFY_IP"],
            ], $config);
            Log::channel("leshuaunion")->info("LogicembedPayResult", $result);
            if ($result["status"] != 1) {
                throw new BizException($result["message"]);
            }
            $response["pre_order"] = $result["data"]["pre_order"] ?? "";

            //入库参数
            $data_insert['out_trade_no'] = $data["orderNo"];
            $data_insert['ways_type'] = $ways->ways_type;
            $data_insert['ways_type_desc'] = $ways->ways_desc;
            $data_insert['ways_source'] = $data['ways_source'];
            $data_insert['company'] = $data['company'];
            $data_insert['ways_source_desc'] = $ways_source_desc;
            $data_insert['other_no'] = $response["pre_order"];
            $insert_re = (new PayBaseController())->insert_day_order($data_insert);
            if (empty($insert_re)) {
                throw new BizException("订单写入失败");
            }


            $resultVo = ResultVo::code("ok")::data($response)::msg("ok");
        } catch (\Exception $e) {
            $resultVo = ResultVo::code("failed")::data(null)::msg($e->getMessage() . "File:" . $e->getFile() . "Line:" . $e->getLine());
        }
        return $resultVo;
    }


    public function getCostRate($ways_type, $user_id)
    {
        $user_rate_obj = UserRate::where('ways_type', $ways_type)
            ->where('user_id', $user_id)
            ->where('status', 1)
            ->orderby('created_at', 'desc')
            ->first();

        return $user_rate_obj;
    }


    public function embedPayParams(array $data, array $config)
    {
        try {
            $response = [
                "AGET_ID" => $config["agetId"],
                "CUST_ID" => $data["custId"],
                "THREE_ORDER_NO" => $data["orderNo"],
                "TxnAmt" => $data["total_amount"],//订单金额 单位分$data["txamt"],
                "ACCESS_TYPE" => "02",
                "PAY_WAY" => "8",
                "interface" => "000002",
                "timeStamp" => date("YmdHis", time()),
                "ASYNC_NOTIFY_IP" => env("APP_URL") . "/api/leshuaunion/embedPayNotify",
                "merchant_id" => $data["merchant_id"],
                "pre_order" => ""
            ];
            /*
                "AGET_ID" => $config["agetId"],
                 "CUST_ID" => $data["custId"],
                 "THREE_ORDER_NO" => $data["orderNo"],
                 "TxnAmt" => $data["total_amount"],//订单金额 单位分$data["txamt"],
                 "ACCESS_TYPE" => "02",
                 "PAY_WAY" => "8",
                 "interface" => "000002",
                 "timeStamp" => date("YmdHis", time()),
                 "ASYNC_NOTIFY_IP" => env("APP_URL") . "/api/leshuaunion/embedPayNotify",
                 "merchant_id" => $data["merchant_id"]
            */
            $pay = new PayController();
            $result = $pay->embedPay([
                "merchant_id" => $response["CUST_ID"],
                "amount" => $data["total_amount"],
                "third_order" => $response["THREE_ORDER_NO"],
                "shop_no" => $data["store_id"],
                "ASYNC_NOTIFY_IP" => $response["ASYNC_NOTIFY_IP"],
            ], $config);
            Log::channel("leshuaunion")->info("LogicembedPayResult", $result);
            if ($result["status"] != 1) {
                throw new BizException($result["message"]);
            }
            $response["pre_order"] = $result["data"]["pre_order"] ?? "";
            $resultVo = ResultVo::code("ok")::data($response)::msg("ok");
        } catch (\Exception $e) {
            $resultVo = ResultVo::code("failed")::data(null)::msg($e->getMessage() . "File:" . $e->getFile() . "Line:" . $e->getLine());
        }
        return $resultVo;
    }


}
